package com.cf.core.stage.impl;

import com.cf.core.event.TicketEvent;
import com.cf.core.player.Player;
import com.cf.core.stage.HeartBeatStage;
import com.cf.game.service.constants.EnumReturnCode;
import com.cf.game.service.exception.BizException;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * game-server-AbsMatchStage
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/11 下午 02:10
 */
@Slf4j
public abstract class AbsNamPartitionMatchStage extends AbsMatchStage {

    protected int partitionNum = 2;

    private Object lock = new Object();

    protected List<Player> matchPlayers = new ArrayList();

    public AbsNamPartitionMatchStage(int heartBeatStep, int stageTime, String stageNum, int partitionNum) {
        super(heartBeatStep, stageTime, stageNum);
        this.partitionNum = partitionNum;
    }


    @Override
    protected void handleTicketEvent(TicketEvent event) {
        //在MatchStage中，心跳消息用来驱动匹配的节奏
        synchronized (lock) {
            matching();
        }
    }

    protected void matching() {
        List<Player> players = getAndResetMatchPlayers();
        if (players == null || players.size() <= 0)
            log.info("当前无用户匹配！【{}】", players.size());
        List<List<Player>> partitions = partitions(players);
        partitions.forEach(partition -> {
            goToGameStage(partition);
        });
    }

    /**
     * 匹配
     *
     * @param players
     * @return
     */
    protected List<List<Player>> partitions(List<Player> players) {
        return Lists.partition(players, partitionNum);
    }

    /**
     * 进入房间
     *
     * @param partition
     */
    protected abstract void goToGameStage(List<Player> partition);

    /**
     * 扣费并加入匹配队列
     */
    public abstract void getMatchTicketAndJoinQueue(Player player);

    private List<Player> getAndResetMatchPlayers() {
        List<Player> players = matchPlayers;
        this.matchPlayers = new ArrayList();
        return players;
    }

    @Override
    protected void clean() {
        throw new BizException(EnumReturnCode.ERROR.getCode(), "当前场景不支持clean方法，调此方法属于异常行为！");
    }

    @Override
    public String getStatue() {
        log.info("匹配房间的状态永远数COMMON");
        return "COMMON";
    }
}
